import React, {
  useEffect,
  useState,
  useRef,
  forwardRef,
  useImperativeHandle,
} from "react";
import "./movieslist.less";

import { moviesApi, moreApi } from "@/api/home";
import useDidUpdateEffect from "../../../../../hooks/useDidUpdateEffect";

import { useNavigate } from "react-router-dom";

const MoviesList = forwardRef((props, ref) => {
  const [moviesList, setMoviesList] = useState([]);
  // const [ids, setIds] = useState([]);
  // const [count, setCount] = useState(0);
  const ids = useRef([]);
  const count = useRef(0);
  const startId = useRef(0);

  const first = useRef(true);

  const navigate = useNavigate();

  useImperativeHandle(ref, () => {
    return {
      async pullUp() {
        const str = ids.current
          .slice(startId.current, startId.current + 6)
          .join(",");
        const res = await moreApi({ ids: str });
        if (res.result) {
          setMoviesList((v) => [...v, ...res.result]);
          // setMoviesList((v) => v.concat(res.result));
          startId.current += 6;
          setTimeout(() => {
            props.onFinishMore();
          }, 0);
        }
      },
    };
  });

  useEffect(() => {
    (async () => {
      const res = await moviesApi();
      setMoviesList(res.result);
      // setIds(res.ids);
      // setCount(res.count);
      ids.current = res.ids;
      count.current = res.count;
      startId.current = res.result.length;

      first.current = false;
    })();
  }, []);

  useDidUpdateEffect(() => {
    props.onScroll();
    // eslint-disable-next-line
  }, [first.current]);

  // useDidUpdateEffect(() => {
  //   console.log("子组件需要加载了");
  // }, [props.count]);

  const goDetail = (id) => () => {
    navigate("/detail/" + id);
  };

  return (
    <ul className="movies">
      {moviesList.map((item, index) => {
        return (
          <li
            key={index}
            className="movies-content"
            onClick={goDetail(item.movieid)}
          >
            <div className="movie-img">
              <img src={item.img.split("/w.h").join("")} alt="" />
            </div>
            <div className="column-content">
              <div className="title">{item.nm}</div>
              <div>
                {item.globalReleased ? (
                  <div>
                    观众评
                    <span className="person">{item.sc}</span>
                  </div>
                ) : (
                  <div>
                    <span className="person">{item.wish}</span>人想看
                  </div>
                )}
              </div>
              <div className="star">主演{item.star}</div>
              <div className="showInfo">{item.showInfo}</div>
            </div>
            {item.globalReleased ? (
              <div className="movie-button1">购票</div>
            ) : (
              <div className="movie-button2">预售</div>
            )}
          </li>
        );
      })}
    </ul>
  );
});

export default MoviesList;
